package com.example.demo.controller.Document;

import com.example.demo.entity.Shop;
import com.example.demo.model.ResponseData;
import com.mongodb.client.result.UpdateResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hanqiang
 * @Classname UpdateDocumentController
 * @Date 2020/10/6 14:10
 * @Description:
 */

@RestController
@RequestMapping("/document")
public class UpdateDocumentController {
    @Autowired
    MongoTemplate mongoTemplate;

    private static final String COMMON_NAME="shops";

    @ApiOperation(value="对集合中数据如果有数据则修改否则添加数据",notes="修改数据")
    @PostMapping("/update")
    public ResponseData update(){
        Query query=new Query(Criteria.where("name").is("橡皮"));
        Update update=new Update();
        update.set("type","学习该生活");
        UpdateResult updateResult=mongoTemplate.upsert(query,update,Shop.class,COMMON_NAME);
        return ResponseData.success(updateResult);
    }

    @ApiOperation(value="对集合中修改数据",notes="修改数据")
    @PostMapping("/updateFirst")
    public ResponseData updateFirst() {

        Query query = Query.query(Criteria.where("name").is("铅笔"));
        Update update = new Update();
        update.set("name", "测试铅笔");
        update.set("price", 123);
        update.set("number",111);
        update.set("type","学习用品");
        update.set("remarks","测试");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Shop.class);
        return ResponseData.success(updateResult);
    }

    /**
     * 修改数据
     */
    @ApiOperation(value="对集合中修改多条数据",notes="修改数据")
    @PostMapping("/updateMulti")
    public ResponseData updateMulti() {
        Query query=new Query(Criteria.where("type").is("学习用品"));
        Update update=new Update();
        update.set("name","han");
        UpdateResult updateResult=mongoTemplate.updateMulti(query,update,Shop.class);
        return ResponseData.success(updateResult);

    }
}
